<template>
  <base-content>
    <template>
      <!-- 查询表单 -->
      <el-main>
        <el-form class="fp-form" :inline="true" label-width="70px">
          <el-form-item label="创建时间">
            <el-date-picker v-model="createTimes" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item label="手机号" prop="name">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="行为类型">
            <el-select v-model="form.operation_type" placeholder="请选择行为类型">
              <el-option label="商品下单提成" :value="1" />
              <el-option label="手动添加" :value="2" />
              <el-option label="提现" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="可售卖范围" label-width="100px">
            <!-- <wlTreeSelect v-model="form.dept_id_list" leaf checkbox :data="treeData" @change="scopeSelectChange" /> -->
            <rm-tree-select
              ref="wl-tree-select"
              v-model="form.dept_id_list"
              check-on-click-node
              node-key="id"
              width="240"
              checkbox
              no-checked-close
              :data="treeData"
              :default-expand-all="false"
              :default-expanded-keys="[1]"
              @change="scopeSelectChange"
            />
          </el-form-item>
          <el-form-item label="积分状态">
            <el-select v-model="form.score_status" placeholder="请选择积分状态">
              <el-option label="冻结" :value="0" />
              <el-option label="可提现" :value="1" />
            </el-select>
          </el-form-item>
          <div class="fp-form-footer">
            <div class="pull-right">
              <el-button v-if="!isHidden" type="primary" @click="handleBaseSearch('add')">添加积分</el-button>
              <el-button type="default" @click="handleBaseSearch('reset')">重置</el-button>
              <el-button type="default" @click="handleBaseSearch('search')">查询</el-button>
            </div>
          </div>
        </el-form>
      </el-main>
      <!-- 积分列表 -->
      <el-table key="btable" v-loading="loading" :data="list">
        <el-table-column prop="insert_time" label="创建时间" />
        <el-table-column prop="user_id" label="用户id" />
        <el-table-column prop="user_score" label="积分" />
        <el-table-column label="行为类型">
          <template slot-scope="scope">
            {{ scope.row.operation_type === 1 ? '商品下单提成' : scope.row.operation_type === 2 ? '手动添加' : scope.row.operation_type === 3 ? '提现' : scope.row.operation_type === 4 ? '从冻结状态转变成可提现状态' : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            {{ scope.row.score_status === 0 ? '冻结' : '可提现' }}
          </template>
        </el-table-column>
        <el-table-column prop="dept_name" label="部门名称" />
        <el-table-column prop="remark" label="备注" />
      </el-table>
      <!-- 分页 控件 -->
      <el-main>
        <el-pagination background layout="prev, pager, next" :total="total" @current-change="pageChange" />
      </el-main>
      <el-dialog title="加积分" :visible.sync="isShow" width="30%">
        <!-- <sf-base-form ref="mybaseForm" :eles="eles" /> -->
        <el-form class="fp-form" :inline="true" label-width="120px">
          <el-form-item label="用户id" prop="name">
            <el-input v-model="addForm.user_id" placeholder="请输入用户ID" />
          </el-form-item>
          <el-form-item label="积分数量" prop="name">
            <el-input v-model="addForm.user_score" type="number" placeholder="请输入积分数量" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="addConfirm">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </base-content>
</template>

<script>
import { mapGetters } from 'vuex'
import { hasPermission, parseTime } from '@/utils'
import { getUserScoreList, addUserScore } from '@/api/coupon'
import { getDeptList } from '@/api/production-api'
import RmTreeSelect from '@/components/sl-tree.vue'

export default {
  components: { RmTreeSelect },
  data() {
    const isHidden = !hasPermission('积分系统')
    return {
      isHidden,
      isShow: false,
      loading: false,
      treeData: [
        {
          id: 'love',
          name: '全平台',
          children: []
        }
      ],
      createTimes: [],
      form: {
        dept_id_list: [],
        start_time: '',
        end_time: '',
        operation_type: '',
        phone: '',
        score_status: ''
      },
      addForm: {
        user_id: '',
        user_score: ''
      },
      list: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      eles: [
        {
          label: '用户ID',
          elType: 'input',
          placeholder: '请输入用户手机号',
          value: '',
          name: 'user_id'
        },
        {
          label: '积分数量',
          elType: 'input',
          placeholder: '输入积分数量',
          value: '',
          name: 'user_score'
        }
      ]
    }
  },
  computed: {
    ...mapGetters(['sidebar']),
    routes() {
      return this.$router.options.routes
    }
  },
  async mounted() {
    if (this.isHidden) {
      this.operations = []
      this.baseHandles = this.baseHandles.filter((item) => item.key !== 'add')
    }
    const result = await getDeptList()
    if (result.code === '0') {
      const list = result.info.data
      this.selsAreas = result.info.data
      // 初始化第一层数据
      const treeList = list.filter((item) => item.dept_parent_id === 0)
      const trees = []
      treeList.forEach((item) => {
        const arr = this.toTreeData(list, item.id)
        trees.push({ id: item.id, name: item.dept_name, children: arr })
      })
      this.treeData[0].children = trees
    } else {
      this.selsAreas = []
    }
    this.query()
  },
  methods: {
    toTreeData(data, pid) {
      function tree(id) {
        const arr = []
        data.filter(item => {
          return item.dept_parent_id === id
        }).forEach(item => {
          arr.push({
            id: item.id,
            name: item.dept_name,
            children: tree(item.id)
          })
        })
        return arr
      }
      // 第一级节点的父id，是null或者0，视情况传入
      return tree(pid)
    },
    scopeSelectChange(val) {
      const scopeIds = val.map((item) => item.id)
      this.form.dept_id_list = scopeIds
    },
    // 添加 确定
    async addConfirm() {
      const result = await addUserScore(this.addForm)
      if (result.code === '0') {
        this.close()
        this.$message.success('添加成功')
        this.query()
      } else {
        this.$message.error(`添加失败：${result.msg}`)
      }
    },
    // 取消添加
    close() {
      this.addForm = {
        user_id: '',
        user_score: ''
      }
      this.isShow = false
    },
    async query(param) {
      const params = {
        page_num: this.pageNum,
        page_size: this.pageSize,
        ...param
      }
      try {
        this.loading = true
        const result = await getUserScoreList(params)
        this.loading = false
        if (result.code === '0') {
          this.list = result.info.data
          this.total = result.info.meta.count
        } else {
          this.loading = false
        }
      } catch (error) {
        this.loading = false
      }
    },
    // 分页事件
    pageChange(val) {
      this.pageNum = val
      this.query({ page_num: val })
    },
    // 查询 添加 重置 按钮
    handleBaseSearch(key) {
      if (this.createTimes.length > 0) {
        this.form.start_time = parseTime(this.createTimes[0])
        this.form.end_time = parseTime(this.createTimes[1])
      }
      if (key === 'search') {
        this.query(this.form)
      } else if (key === 'add') {
        this.isShow = true
      } else {
        this.form = {
          dept_id_list: [],
          start_time: '',
          end_time: '',
          operation_type: '',
          phone: '',
          score_status: ''
        }
        this.createTimes = []
        this.query(this.form)
      }
    }
  }
}
</script>
